/* Author: Nahuel F. Lema, Maxi Yañez

 */

var compartiTuPuntoController = {
    selects: {
        provincia: null,
        localidad: null,
        init: function () {
            this.provincia = document.getElementById('selectProvincia');
            this.localidad = document.getElementById('selectLocalidad');
            this.provincia.className = 'field span';
            this.localidad.className = 'field span';
            this.disabled('localidad');
            this.bind();
        },
        reload: function () {
            this.provincia = document.getElementById('selectProvincia');
            this.localidad = document.getElementById('selectLocalidad');
            this.provincia.className = 'field span';
            this.localidad.className = 'field span';
            this.bind();
        },
        bind: function () {
            var self = this;
            this.provincia.onchange = function () {
                var id = this.value;
                var padre = self.localidad.parentNode;
                if (id) {
                    $.ajax({
                        url: scriptsController.defs.baseUrl+'controllers/select/localidadesByProvincia/'+id,
                        type: 'POST',
                        success: function(data) {
                            padre.removeChild(self.localidad);
                            padre.innerHTML += data;
                            self.reload();
                        }
                    });
                } else {
                    self.disabled('localidad');
                }
            }
        },
        disabled: function (select) {
            this[select].innerHTML = '<option value="">Elegir</option>';
            this[select].disabled = 'disabled';
        }
    },
    
    map: {
        options: {
            app: {
                zoom: 13,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                disableDefaultUI: true,
                zoomControl: true,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL
                }
            },
            markers:[],
            geocoder: new google.maps.Geocoder(),
            latLngBounds: new google.maps.LatLngBounds(new google.maps.LatLng(-54.952386,-73.081055),new google.maps.LatLng(-22.105999,-53.613281)),
            center: new google.maps.LatLng(-34.603526, -58.381586),
            coordenadas:'coordenadas',
            direccion:'geolocalizacion'
        },
        bindDireccion : function () {
            var self = this;
            $('#'+self.options.direccion).bind('keypress', function(e) {
                if(e.keyCode==13){
                    if ($("#"+self.options.direccion).val()) {
                        self.buscar();
                    }
                    return false;
                }
            });
            $('#bnt-buscar').click(function () {
                if ($("#"+self.options.direccion).val()) {
                        self.buscar();
                    }
                    return false;
            })
            $('#'+self.options.coordenadas).bind('keypress', function(e) {
                var self = this;
                if(e.keyCode==13) {
                    var LatLng = $(this).val().split(', ');
                    var centro = new google.maps.LatLng(LatLng[0], LatLng[1]);
                    self.app.setZoom(15);
                    self.app.setCenter(centro);
                    var marker = new google.maps.Marker({map: self.app,position: centro});
                    marker.setMap(self.app);
                    self.bindMarker(marker);
                    return false;
                }
            })
        },
        buscar: function () {
            var self = this;
            var direccion = $('#'+self.options.direccion).val();
            var request = {
                language: 'es',
                region: 'AR',
                address: direccion + ' Argentina'
            }
            self.options.geocoder.geocode(request, function(results, status) {
                if(status == google.maps.GeocoderStatus.OK) {
                    self.centarMapa(results);
                    return results;
                }
                return status;
            });
        },
        centarMapa: function(geocodes) {
            var self = this, latLng = {}, marker = {},
            bounds = new google.maps.LatLngBounds ();
            self.clearMarkers();
            if (geocodes.length > 1) {
                for (var i in geocodes) {
                    latLng = geocodes[i].geometry.location;
                    bounds.extend(latLng);
                    marker = new google.maps.Marker({map: self.app,position: latLng});
                    marker.setMap(self.app);
                    self.options.markers.push(marker);
                    self.bindMarker(marker);
                }
                self.app.fitBounds(bounds);
                $('#alertManyMarkers').show();
            } else if (geocodes.length == 1) {
                latLng = geocodes[0].geometry.location;
                marker = new google.maps.Marker({map: self.app,position: latLng,  draggable:true});        
                marker.setMap(self.app);
                self.options.markers.push(marker);
                self.asignarCoordenadas(marker);
                self.app.setCenter(geocodes[0].geometry.location);
                self.app.setZoom(15);
                self.bindMarker(marker);
                $('#alertHelper').show();
            } else {
                $('#alertNoMarkers').show();
            }
        },      
        bindMarker: function (marker) {
            var self = this;
            google.maps.event.addListener(marker, 'click', function() {
                self.options.markers.push(marker);
                self.clearMarkers();
                self.app.setZoom(15);
                self.asignarCoordenadas(marker);
                marker.setMap(self.app);
                marker.setDraggable(true);
                $('#alertManyMarkers, #alertHelper, #alertNoMarkers').hide();
            });
            google.maps.event.addListener(marker, 'dragend', function() {
                self.asignarCoordenadas(marker);
                $('#alertManyMarkers, #alertHelper, #alertNoMarkers').hide();
            });
        },
        clearMarkers: function () {
            var self = this;
            $('#'+self.options.coordenadas).val('');
            $('#alertManyMarkers, #alertHelper, #alertNoMarkers').hide();
            for (var i=0, l=self.options.markers.length; i<l; i++ ) {
                self.options.markers[i].setMap(null);
            }
            self.options.markers = [];
        },
        asignarCoordenadas: function (marker) {
            $('label[for="coordenadas"]').remove();
            var self = this, latLng = {}, text='';
            self.app.setCenter(marker.getPosition());
            latLng = marker.getPosition();
            text = latLng+'';
            text = text.replace('(', '')
            text = text.replace(')', '')
            $('#'+self.options.coordenadas).val(text);
        },
        init: function () {
            this.app = new google.maps.Map(document.getElementById("map"), this.options.app);
            this.app.setCenter(this.options.center);
            this.bindDireccion();
        }
    },
    
    categoriasToCheck: {
        create:function () {
            var html = '';
            $.ajax({
                url:scriptsController.defs.baseUrl+'controllers/categoriaController/findAll',
                success:function (data) {
                    for (var i in data.categorias) {
                        html += '\
                            <li class="span2">\
                                <label for="'+data.categorias[i].identificador+'-field" class="field-container '+data.categorias[i].identificador+'-field checkbox inline">\
                                    <input type="checkbox" value="'+data.categorias[i].id+'" name="categorias[]" id="'+data.categorias[i].identificador+'-field" class="field"/>\
                                    <b class="title">'+data.categorias[i].nombre+'</b>\
                                </label>\
                            </li>\
                        '
                    }
                    $('.category-list').html(html)
                    compartiTuPuntoController.categorias.init();
                }
            })
        }
    },
    
    categorias: {
        bindCategorias:function () {
            var self = this;
            $('.checkbox input').change(function () {
                var input = $(this);
                $('.subcategorias-container[data-id="'+$(this).val()+'"]').slideToggle(400, function () {
                    if (!$(input).is(':checked')) {
                        self.deselectAllSubcategorias($(input).val());
                        $(this).find('span.error').remove();
                    }
                });
            })
        },
        bindSubcategorias: function () {
            var self = this;
            $('.subcategorias-container li').click(function () {
                $(this).toggleClass('active');
                if ($(this).hasClass('active')) {
                    $(this).find('input').val($(this).find('a').data('id'))
                    $(this).parent().parent().find('span.error').remove();
                } else {
                    $(this).find('input').val(0);
                }
            })
            $('.subcategorias-container p').click(function () {
                var li = $(this).parent().find('li');
                if ($(li).hasClass('active')) {
                    self.deselectAllSubcategorias($(this).parent().data('id'));
                } else {
                    self.selectAllSubcategorias($(this).parent().data('id'));
                }
            })
        },
        selectAllSubcategorias: function (categoriaId) {
            $('.subcategorias-container[data-id="'+categoriaId+'"] li').each(function () {
                $(this).addClass('active');
                $(this).find('input').val($(this).find('a').data('id'));
            })
        },
        deselectAllSubcategorias: function (categoriaId) {
            $('.subcategorias-container[data-id="'+categoriaId+'"] li').removeClass('active')
            $('.subcategorias-container[data-id="'+categoriaId+'"] input').val(0);
        },
        validar: function () {
           $('.subcategorias-container:visible').each(function () {
               if(!$(this).find('li.active').length) {
                   $(this).find('p').append(' <span class="error">Ten&eacute;s que seleccionar al menos una subcategor&iacute;a</span>')
               }
           })
        },
        init: function () {
            this.bindCategorias();
            this.bindSubcategorias();
        }
    },

    validate: {

        get: function(){
            var componentsPath = scriptsController.defs.baseUrl + scriptsController.defs.componentsPath + 'jvalidation/',
            self = this;
            $.getScript(componentsPath + 'jquery.validate.min.1.9.js', function(){
                self.bind();
            });
        },

        bind: function(){
            var form = $(js.get.item('#comparti-tu-punto-form')[0]);
            $(js.get.item('#cargar-tu-punto-btn')[0]).click(function(e){
                e.preventDefault();
                form.submit();
            });

            form.validate({
                ignore: "",
                errorPlacement: function(error, element) {
                    if ($(element).attr('name') == 'categorias[]') {
                        error.appendTo($('#errorCategorias'));
                    } else {
                        error.insertAfter(element);
                    }
                },
                rules: {
                    'coordenadas' : {
                        required : true
                    },
                    'nombre' : {
                        required : true
                    },
                    'email' : {
                        required : true,
                        email	 : true
                    },
                    'calle' : {
                        required : true
                    },
                    'numero' : {
                        required : true
                    },
                    'horario':{
                        required : true
                    },
                    'telefono': {
                        required : true
                    },
                    'provincia' : {
                        required : true
                    },
                    'localidad' : {
                        required : true
                    },
                    'quienes' : {
                        required : true,
                        minlength: 10
                    },
                    'que' : {
                        required : true,
                        minlength: 10
                    },
                    /*'porque' : {
                        required : true,
                        minlength: 10
                    },*/
                    'comentario' : {
                        required : true,
                        minlength: 10
                    },
                    'categorias[]': {
                        required : true, 
                        minlength: 1 
                    }
                },
                messages: {
                    'coordenadas' : {
                        required : "Ten&eacute;s que ubicar el punto"
                    },
                    'nombre' : {
                        required : "Este campo es obligatorio"
                    },
                    'email' : {
                        required : "Este campo es obligatorio",
                        email	 : "Ingrese un email v&aacute;lido"
                    },
                    'calle' : {
                        required : "Este campo es obligatorio"
                    },
                    'numero' : {
                        required : "Este campo es obligatorio"
                    },
                    'horario':{
                        required : "Este campo es obligatorio"
                    },
                    'telefono': {
                        required : "Este campo es obligatorio"
                    },
                    'provincia' : {
                        required : "Este campo es obligatorio"
                    },
                    'localidad' : {
                        required : "Este campo es obligatorio"
                    },
                    'quienes' : {
                        required : "Este campo es obligatorio",
                        minlength: "Ingrese un minimo de 10 caracteres"
                    },
                    'que' : {
                        required : "Este campo es obligatorio",
                        minlength: "Ingrese un minimo de 10 caracteres"
                    },
                    /*'porque' : {
                        required : "Este campo es obligatorio",
                        minlength: "Ingrese un minimo de 10 caracteres"
                    },*/
                    'comentario' : {
                        required : "Este campo es obligatorio",
                        minlength: "Ingrese un minimo de 10 caracteres"
                    },
                    'categorias[]': 'Ten&eacute;s que seleccionar al menos una categor&iacute;a'
                },
                submitHandler: function($form) {
                    compartiTuPuntoController.categorias.validar();
                    if (!$('.subcategorias-container span.error').length) {
                        scriptsController.fixedLoader.show();
                        $form.submit();
                    }
                },
                invalidHandler: function () {
                    compartiTuPuntoController.categorias.validar();
                }
            });
        },

        init: function(){
            this.get();
        }
    },

    init: function(){
        this.categoriasToCheck.create();
        this.selects.init();
        this.validate.init();
        this.map.init();
    }
}

compartiTuPuntoController.init();